//
//  ScriptHelper.m
//  ReplaceImagesInAssets
//
//  Created by liboxiang on 2019/4/15.
//  Copyright © 2019 liboxiang. All rights reserved.
//

#import "ScriptHelper.h"

@implementation ScriptHelper

+ (NSString *)runScript:(NSString *)scriptName type:(NSString *)type launchPath:(NSString *)launchPath arguments:(NSArray *)arguments {
    //脚本路径
    NSString *shellPath = [[NSBundle mainBundle] pathForResource:scriptName ofType:type];
    return [ScriptHelper runScriptAtPath:shellPath launchPath:launchPath arguments:arguments];
}

+ (NSString *)runScriptAtPath:(NSString *)path launchPath:(NSString *)launchPath arguments:(NSArray *)arguments
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:launchPath];
    //数组index 0 shell路径, 如果shell 脚本有输入参数,可以加入数组里，index 1 可以输入$1 @[path,@"$1"],依次延后。
    NSMutableArray *arg = [NSMutableArray arrayWithObject:path];
    [arg addObjectsFromArray:arguments];
    [task setArguments: arg];
    NSPipe *pipe = [NSPipe pipe];
    task.standardOutput = pipe;
    task.standardError = pipe;
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    [task waitUntilExit];
    NSData *data;
    data = [file readDataToEndOfFile];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}


@end
